<?php

namespace App\Http\Middleware;

use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 *
 */
class ApiPre
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            if ($user) {
                try {
                    if ($user->learnQuestionOfLastTime == null || !Carbon::make($user->learnQuestionOfLastTime)->isToday()) {
                        $user->learnQuestionOfLastTime = now();
                        $user->learnQuestionCountOfToday = 0;
                        $user->correctQuestionCountOfToday = 0;
                        $user->wrongQuestionCountOfToday = 0;

                        // 清空统计缓存
                        $redisBaseService = new RedisBaseService();
                        $redisBaseService->delUserStatisticsData('statistics:userLearnQuestionOfTodayCount', $user->id);
                        $redisBaseService->delUserStatisticsData('statistics:userCorrectQuestionCountOfToday', $user->id);
                        $redisBaseService->delUserStatisticsData('statistics:userWrongQuestionCountOfToday', $user->id);
                    }
                }catch (\Exception $e) {
                    \Log::error('[清空当天缓存失败]：'.$e->getMessage());
                    \Log::error($e);
                }
            }
        }
        return $next($request);
    }
}
